<template>
  <div class="csr" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" @changeType="changeType" :query="query" :isTimePeriod = "true" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{$t('report.imAccessId')}}：</span>
                  <el-select size="mini" v-model.trim="selectedAccessIdList" multiple filterable :placeholder="$t('report.searchByName')">
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
                <div class="agent_search">
                  <div class="skill">
                    <el-radio-group v-model="radio1"
                                  size = "mini"
                                  @change = "changeAgentBig">
                      <el-radio :label="1">{{$t('report.lookAgentWork')}}</el-radio>
                      <el-radio :label="0">{{$t('report.lookSkillWork')}}</el-radio>
                      <span class="tip">
                        <el-tooltip
                          transition="fade-leave"
                          effect="dark"
                          :content="$t('report.queueChangeAgentTip')"
                          placement="bottom">
                          <i class="icon iconfont icon-tixingweizhi"></i>
                        </el-tooltip>
                      </span>
                    </el-radio-group></div>
                  <div class="wrap_conti" v-show="radio1">
                    <span class="chan_ag">{{$t('report.chooseAgent')}}:</span>
                    <el-radio-group v-model="radio3"
                                  size = "mini"
                                  @change = "changeAgent">
                      <div>
                        <el-radio :label="1">{{$t('public.checkAll')}}</el-radio></div>
                      <div :class="[{wrap_agents: wrapAgents}, 'skill']">
                        <el-radio :label="2">{{$t('report.accordAgentChoose')}}</el-radio>
                        <!-- <el-select v-model="selectedAgentList"
                                   multiple
                                   filterable
                                   :disabled = "radio3 !== 2"
                                   size="mini"
                                   @change="agentsChange"
                                   :placeholder="$t('report.pleChoseAgent')">
                            <el-option
                              v-for="item in agentOptions"
                              :label="item.label"
                              :value="item.value"
                              :key="item.value">
                            </el-option></el-select> -->
                        <m7Select class="el-select" :disabled = "radio3 !== 2" filterable multiple :options="selectAgents" v-model="selectedAgentList"></m7Select>
                        <el-checkbox :disabled = "radio3 !== 2"
                                     v-model.trim="query.includeSubordinate">
                          {{$t('public.includeSubordinate')}}</el-checkbox></div>
                      <div class="skill">
                        <el-radio :label="3">{{$t('report.chooseSkillAgent')}}</el-radio>
                        <el-select size="mini"
                                   v-model.trim="currentQueue"
                                   :placeholder="$t('report.queueNaSea')"
                                   multiple
                                   :disabled = "radio3 !== 3"
                                   filterable
                                   @change = "change">
                          <el-option v-for="item in mailQueues"
                                     :label="item.DisplayName"
                                     :value="item._id"
                                     :key="item._id"></el-option>
                        </el-select>
                        <el-checkbox :disabled = "radio3 !== 3"
                                       v-model.trim="isShowAgent">
                            {{$t('report.isShowSkillAgent')}}</el-checkbox></div>
                      <div class="skill dept" v-show="!flag">
                        <el-radio :label="4">{{$t('report.accordDeptChoose')}} </el-radio>
                        <el-select size="mini"
                                   v-model.trim="currentdept"
                                   :placeholder="$t('report.deptNaSea')"
                                   multiple
                                   :disabled = "radio3 !== 4"
                                   filterable
                                   @change = "changeDept">
                          <el-option v-for="item in depts"
                                     :label="item.name"
                                     :value="item.treePath"
                                     :key="item._id"></el-option>
                        </el-select>
                        <el-checkbox :disabled = "radio3 !== 4"
                                     v-model.trim="isShowDeptAgent"
                                     @change="changeShowDept">
                            {{$t('report.isShowDeptAgent')}}</el-checkbox></div>
                    </el-radio-group>
                  </div>
                  <div class="wrap_conti" v-show="!radio1">
                    <div class="skill">
                      <span class="ski">{{$t('report.chooseSkill')}}:</span>
                      <el-select size="mini"
                                     v-model.trim="currentQueueS"
                                     :placeholder="$t('report.queueNaSea')"
                                     filterable
                                     @change = "changeSkill">
                        <el-option v-for="item in mailQueues"
                                   :label="item.DisplayName"
                                   :value="item.Exten"
                                   :key="item._id"></el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.imSurveyOverview')"></affix>
      <div class="situation">
        <el-row>
          <el-col v-for="(item, index) in situation" :span="6" :key="index">
            <span class="sum_name">{{item.name}}</span>
            <span class="sit_num">{{item.value}}</span>
          </el-col>
        </el-row>
      </div>
      <affix :label="title"></affix>
    </div>
    <div v-show="!isShowDetail" class="tab" :id = "id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div>
        <div class="export">
          <el-button class="primary_btn fr formal" v-if="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd && !flag"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            v-if="!flag"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-button class="primary_btn fr pdf" v-show="isShowDetailExport && !flag" v-on:click.stop="exportXls(true)">{{$t('report.imExportDetailXls')}}
          </el-button>
          <el-button class="primary_btn fr pdf" v-on:click="showDetail">{{$t('call.queryDetail')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                1. {{$t('report.imSessionAllNum')}} <br>
                2. {{$t('report.imAllEvaluateNum')}} <br>
                3. {{$t('report.agentPushCount')}} <br>
                4. {{$t('report.totalPushCount')}} <br>
                5. {{$t('report.AgentInvitateRate')}} <br>
                6. {{$t('report.sendInvitedProport')}} <br>
                7. {{$t('report.oldParticipationRate')}} <br>
                8. {{$t('report.participationRate')}}<br>
                9. {{$t('report.agentPushSucceedCount')}}<br>
                <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{index + 10}}.{{item.formulaInstr}}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="[...headOptions.Config, ...formulasConfig]"></report-table>
      </div>
    </div>
    <suevey-detail :formulas="formulas" @exportPdf="exportPdf" @close="returnCur" @exportXlsx="exportXlsx" v-show="isShowDetail" :data="tableData" :customHeader="formulasConfig" :sum="totalData" :config="headOptions.Config"></suevey-detail>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config" @closeFormulaDialog="closeFormulaDialog" :reportType="id"/>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import sueveyDetail from './ImReportCsrDetail.vue'
  import reportTable from '../base/crsTable.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import { deepClone, optionTimeTypeCheck, getFormatTimeBySecond, isHasFunc } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr, mixData } from '@/utils/reportUtils.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  export default {
    name: 'im_report_csr',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        exCludesKey: ['agentExten', 'agentName', 'sessionCount', 'totalAppraiseCount', 'agentId', 'appraiseRate', 'agentInviteRate', 'appraiseRateOld', 'agentPushCount', 'totalPushCount', 'inviteRate', 'agentPushSucceedCount'],
        flag: this.$store.getters.isEcommerce ? true : false, // 是否是电商平台
        isShowDetail: false, // 是否展示满意度评价详情
        dateType: 'day', // 当前选择时间类型
        isSearch: false, // 查询时不触发监听自定义表头的变化
        formulas: [], // 公式数据
        wrapAgents: false, // 是防止座席数据量展示太大设置样式index -1
        isShowAgent: false, // 是否展示技能组下的座席
        isShowDeptAgent: false, // 是否展示部门下的座席
        accessIdOptions: [], // 接入号数据
        selectedAccessIdList: [], // 接入号绑定值
        selectedAgentList: [], // 座席id集合
        selectedAgentListClone: [], // 是否展示座席得复制版
        isFold: false, // 是否展示搜索条件
        currentQueueS: '', // 技能组号
        radio3: 1, // 各座席工作量下面选择切换绑定得值
        radio1: 1, // 各座席工作量和各技能组切换绑定值
        depts: [], // 部门渲染下拉数据
        situation: [], // 概况数据
        currentdept: [], // 选择部门绑定得id值集合
        currentQueue: [], // 各座席工作量下技能组绑定值
        mailQueues: [], // 技能组信息集合
        id: 'im_report_csr',
        title: this.$t('report.imReportCsr'),
        loading: false,
        query: {includeSubordinate: false},
        dialogVisible: false,
        agentOptions: [], // 渲染座席数据
        serverData: [], // 查询出来的原始表格数据
        headOptions: { Config: [], data: [] },
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.imReportCsr') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            formatter: function () {
              var tip = '<span style="font-size:10px">' + this.x + '</span><br>'
              this.points.map((item, index) => {
                var unit = ''
                if (item.series.name.slice(-1) === '率' || item.series.name.slice(-2) === '占比' || item.series.name.slice(-1) === '）') {
                  unit = '%'
                } else if (item.series.name.slice(-1) !== '率' && item.series.name.slice(-1) !== '数' && item.series.name.slice(-2) !== '占比') {
                  unit = this.points[1].y > 0 ? `(${(item.y / this.points[1].y * 100).toFixed(1)}%)` : '(0%)'
                }
                tip += '<span style="color:' + item.series.color + '">\u25CF</span>' + item.series.name + ': <b>' +
                  item.y + '' + unit + '</b><br>'
              })
              return tip
            },
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      sueveyDetail,
      reportTable,
      FormulaEditorDialog
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serverData || this.serverData.length === 0) {
          return
        }
        this.serverData = mixData(deepClone(this.serverData), this.formulas)
      },
      // 是否展示技能组下的座席
      isShowAgent (cur) {
        if (cur) {
          this.selectedAgentList = this.selectedAgentListClone
          this.wrapAgents = false
        } else {
          this.selectedAgentList = []
        }
      }
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agentOptions
      },
      // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['month']
        return type.includes(this.dateType)
      },
      tableData () {
        return this.getTableData(this.serverData)
      },
      totalData () {
        this.situation = []
        if (!this.serverData || this.serverData.length === 0) {
          // 渲染概况
          let headerConfig = this.headOptions.Config || []
          for (let i = 0; i < headerConfig.length; i++) {
            if (headerConfig[i].name !== 'agentName') {
              this.situation.push({name: headerConfig[i].displayname, value: 0})
            }
          }
          return [{agentName: this.$t('report.total')}]
        }
        let headerConfig = this.headOptions.Config || []
        let total = this.getTotalData(this.serverData, this.headOptions)[0]
        // 渲染概况
        for (let i = 0; i < headerConfig.length; i++) {
          if (headerConfig[i].name !== 'agentName') {
            this.situation.push({name: headerConfig[i].displayname, value: total[headerConfig[i].name]})
          }
        }
        return mixData([total], this.formulas)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }
        let highchartsTitle = ''
        if (this.query.timePeriod) {
          let timePeriodStartStr = this.query.timePeriodStart || '00:00'
          let timePeriodEndStr = this.query.timePeriodEnd || '23:59'
          highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
        }
        this.highchartsDefaultOptions.title.text = this.$t('report.imReportCsr') + highchartsTitle
        let headerConfig = this.headOptions.Config || []
        let datas = deepClone(this.serverData)
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'agentName') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'appraiseRate' || item.name === 'appraiseRateOld' || item.name === 'agentInviteRate' || item.name === 'inviteRate') {
            serie.tooltip = { valueSuffix: '%' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.getAgentName(datas[i].agentId))
          for (let j = 0; j < seriesArray.length; j++) {
            if (seriesArray[j].valueName === 'appraiseRate' || seriesArray[j].valueName === 'appraiseRateOld' || seriesArray[j].valueName === 'agentInviteRate' || seriesArray[j].valueName === 'inviteRate') {
              datas[i][seriesArray[j].valueName] = parseFloat(datas[i][seriesArray[j].valueName])
            }
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray
        return options
      },
      // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      }
    },
    methods: {
      returnCur () {
        this.isShowDetail = false
      },
      // 展示满意度详情页
      showDetail () {
        this.isShowDetail = true
      },
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 处理table数据
      getTableData (serverData, isExport) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)
        return this.computData(data, isExport)
      },
      // 获取合计总数
      getTotalData (datas, headerConfig, isExport) {
        // let headerConfig = this.headOptions.Config || []
        // let datas = this.serverData
        let total = {
          agentName: this.$t('report.total'),
          totalAppraiseCount: 0,
          sessionCount: 0
        }
        for (var i in datas) {
          let item = datas[i]
          for (var j in item) {
            if (total[j] === undefined) {
              total[j] = 0
            }
            if (j !== 'agent_name') {
              total[j] += item[j]
            }
          }
        }
        // 参评率
        total.appraiseRate = total.totalPushCount > 0 ? ((total.totalAppraiseCount / total.totalPushCount) * 100).toFixed(1) : '0.0'
        // 旧参评率
        total.appraiseRateOld = total.sessionCount > 0 ? ((total.totalAppraiseCount / total.sessionCount) * 100).toFixed(1) : '0.0'
        // 座席邀请率
        total.agentInviteRate = total.totalPushCount > 0 ? ((total.agentPushCount / total.totalPushCount) * 100).toFixed(1) : '0.0'
        // 发送评价数量占比
        total.inviteRate = total.sessionCount > 0 ? ((total.totalPushCount / total.sessionCount) * 100).toFixed(1) : '0.0'
        // 不同评价的概率
        for (let key in total) {
          if (!this.exCludesKey.includes(key) && key.indexOf('_') === -1) {
            if (isExport) {
              total[key + '_rate'] = total.totalAppraiseCount > 0 ? (total[key] * 100 / total.totalAppraiseCount).toFixed(1) + '%' : `0.0%`
            } else {
              total[key] = total.totalAppraiseCount > 0 ? `${total[key]}(` + (total[key] * 100 / total.totalAppraiseCount).toFixed(1) + '%)' : `${total[key]}(0.0%)`
            }
          }
        }
        this.headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            total[option.name] = getFormatTimeBySecond(total[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            total[option.name] = Math.round(total[option.name]) + 's'
          } else if (option.name.indexOf('Rate') > -1 && (option.displayname.indexOf('率') > -1 || option.displayname.indexOf('占比') > -1)) {
            total[option.name] = `${total[option.name]}%`
          }
        })
        return mixData([total], this.formulas)
      },
      // 座席组件改变得事件
      agentsChange () {
        if (this.wrapAgents) {
          this.wrapAgents = false
        }
      },
      // 是否展示部门下的座席
      changeShowDept (cur) {
        if (cur) {
          this.wrapAgents = false
          this.selectedAgentList = this.selectedAgentListClone
        } else {
          this.selectedAgentList = []
          this.wrapAgents = true
        }
      },
      // 展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 各座席工作量和技能组切换, 初始化一些数据
      changeAgentBig (num) {
        delete this.query.queryExten
        this.currentQueueS = ''
        this.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentQueue = []
        this.currentdept = []
        this.query.includeSubordinate = false
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.wrapAgents = false
      },
      // 切换按技能组查询下技能组触发方法 技能组号赋值给查询条件
      changeSkill (id) {
        this.query.queryExten = id
      },
      // 座席下拉切换执行得方法
      changeAgent () {
        this.selectedAgentList = []
        this.currentQueue = []
        this.currentdept = []
        this.selectedAgentListClone = []
        this.query.includeSubordinate = false
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.wrapAgents = false
      },
      // 部门切换执行得方法 筛选座席
      changeDept (deptTreePaths) {
        this.selectedAgentList = []
        this.selectedAgentListClone = []
        let deptIds = [] // 创建部门id数组集
        if (deptTreePaths.length !== 0) {
          for (let i = 0; i < deptTreePaths.length; i++) {
            if (deptTreePaths[i] === 'noDept') {
              deptIds.push('')
            } else {
              let deptIdArr = deptTreePaths[i].split('/')
              // deptIdArr长度为2为根部门
              if (deptIdArr.length === 2) {
                this.agentOptions.map(item => {
                  this.selectedAgentListClone.push(item.value)
                })
                if (this.isShowDeptAgent) {
                  this.selectedAgentList = this.selectedAgentListClone
                }
                break
              }
              let deptId = deptIdArr[deptIdArr.length - 2] // 当前部门id
              deptIds.push(deptId) // 像部门数组中添加当前部门id
              for (let j = 0; j < this.depts.length; j++) {
                let isDeptIdArr = this.depts[j].treePath.split(deptId + '/')[1] // 判断当前部门下面得部门是否存在
                if (isDeptIdArr) {
                  deptIds = deptIds.concat(isDeptIdArr.split('/').filter(item => item))
                }
              }
            }
          }
          deptIds = Array.from(new Set(deptIds)) // 部门id去重
          let cloneAgentsArr = []
          cloneAgentsArr = this.agentOptions.filter(item => { // 过滤座席信息得部门是否在部门数组里，是则返回
            return deptIds.includes(item.deptId)
          })
          cloneAgentsArr.map(item => {
            this.selectedAgentListClone.push(item.value)
          })
          if (this.isShowDeptAgent) {
            this.selectedAgentList = this.selectedAgentListClone
          }
        }
      },
      // 查看各座席下的技能组切换执行得 筛选座席方法
      change (peerIds) {
        this.selectedAgentListClone = []
        this.selectedAgentList = []
        this.includeSubordinate = false
        if (peerIds.length === 0) {
          return
        }
        let agentIds = []
        peerIds.map((id) => {
          this.mailQueues.map((item) => {
            if (item._id === id) {
              agentIds = agentIds.concat(item.AssignMembers)
            }
          })
        })
        agentIds.map((obj) => {
          if (obj) {
            this.selectedAgentListClone.push(obj.agentID)
          }
        })
        if (this.isShowAgent) {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
          this.selectedAgentList = this.selectedAgentListClone
        } else {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
        }
      },
      computData (data, isExport) {
        // let noAddPercent = ['agentExten', 'agentName', 'totalAppraiseCount', 'agentId', 'appraiseRate', 'agentId', 'agentId', 'agentInviteRate', 'agentId']
        data.forEach(item => {
          if (isExport) {
            var {displayName, exten} = this.getAgentDisplayNameAndExten(item.agentId)
            item.agentName = displayName
            item.agentExten = exten
          } else {
            item.agentName = this.getAgentName(item.agentId)
          }
          for (let key in item) {
            if (!this.exCludesKey.includes(key) && key.indexOf('_') === -1) {
              if (isExport) {
                item[key + '_rate'] = item.totalAppraiseCount > 0 ? (item[key] * 100 / item.totalAppraiseCount).toFixed(1) + '%' : `0.0%`
              } else {
                item[key] = item.totalAppraiseCount > 0 ? `${item[key]}(` + (item[key] * 100 / item.totalAppraiseCount).toFixed(1) + '%)' : `${item[key]}(0.0%)`
              }
            }
          }
          this.headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getFormatTimeBySecond(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = item[option.name] + 's'
            } else if (option.name.indexOf('Rate') > -1 && (option.displayname.indexOf('率') > -1 || option.displayname.indexOf('占比') > -1)) {
              item[option.name] = `${item[option.name]}%`
            }
          })
        })
        return data
      },
      // 通过座席id返回座席姓名和工号string
      getAgentName (id) {
        let agent = this.$store.getters.agents[id]
        let getAgent = agent ? agent.displayName + '(' + agent.exten + ')' : ''
        return getAgent
      },
      // 通过座席id返回座席姓名和工号obj
      getAgentDisplayNameAndExten (id) {
        let agent = this.$store.getters.agents[id]
        return {
          displayName: agent ? agent.displayName : '',
          exten: agent ? agent.exten : ''
        }
      },
      // 查询条件
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        query.selectedAgentList = this.selectedAgentList.join(',')
        if (this.selectedAgentListClone.length > 0) {
          query.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        // 选择部门或技能组 但其下面无座席 故传显示无座席得值
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          query.selectedAgentList = '000000'
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryImCsrReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.isSearch = true
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
            if (resp.success) {
              this.formulas = resp.data.Formulas
              // 表头
              this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
              this.serverData = deepClone(mixData(res.data, this.formulas)) || deepClone(this.serverData)
              this.loading = false
            }
          })
          //  图表标题 加入 定时段的 时间
          let highchartsTitle = ''
          if (this.query.timePeriod) {
            let timePeriodStartStr = this.query.timePeriodStart || '00:00'
            let timePeriodEndStr = this.query.timePeriodEnd || '23:59'
            highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
          }
          this.highchartsDefaultOptions.title.text = this.$t('report.imReportCsr') + highchartsTitle
        })
      },
      exportXls (bool) {
        let data = {
          Method: 'exportImCSR',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        // 导出详细excel更改method
        if (bool === true) {
          data.Method = 'exportImCSRDetail'
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        query.selectedAgentList = this.selectedAgentList.join(',')
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        if (this.selectedAgentListClone.length > 0) {
          query.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          query.selectedAgentList = '000000'
        }
        data.Query.detailed = false
        if (bool === 'detail') {
          data.Query.detailed = true
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImCsrReport', data)
      },
      // 处理详情页得导出
      dealDetailExport (tableData, Config, Length) {
        let exportArr = []
        let row = 1
        let curCol = 0
        let isSetDetail = false // 判断是否有二级满意度
        for (let i = 0; i < Config.length; i++) {
          if (Config[i].sub && Config[i].sub.length) {
            isSetDetail = true
          }
        }
        let currentCol = 0
        let configLen = Length
        Config.forEach((item, index) => {
          let dataRow = isSetDetail ? 3 : 2 // 判断data从第几行开始
          currentCol++
          if (item.sub && item.sub.length) {
            // 合并添加至末尾
            exportArr.push({
              value: item.displayname,
              startRow: row,
              startCol: configLen + 1,
              endRow: row,
              merged: true,
              endCol: configLen + item.sub.length
            })
            // 正常循环
            exportArr.push({
              value: item.displayname,
              startRow: row,
              startCol: currentCol,
              endRow: row + 1,
              merged: true,
              endCol: currentCol
            })
            exportArr = exportArr.concat(this.renderTwoRow(item.sub, configLen, tableData))
            configLen = configLen + item.sub.length
          } else {
            if (isSetDetail) {
              if (item.name.indexOf('_formulas_') > -1) {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: configLen + 1 + curCol,
                  merged: true,
                  endRow: 2,
                  endCol: configLen + 1 + curCol
                })
                curCol++
              } else {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: currentCol,
                  merged: true,
                  endRow: 2,
                  endCol: currentCol
                })
              }
            } else {
              if (item.name.indexOf('_formulas_') > -1) {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: configLen + 1 + curCol,
                  merged: true,
                  endRow: row,
                  endCol: configLen + 1 + curCol
                })
                curCol++
              } else {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: currentCol,
                  endRow: row,
                  endCol: currentCol
                })
              }
            }
          }
          for (let k = 0; k < tableData.length; k++) {
            let curObj = tableData[k]
            if (item.name.indexOf('_formulas_') > -1) {
              exportArr.push({
                value: curObj[item.name],
                startRow: dataRow,
                startCol: configLen + curCol,
                endRow: dataRow,
                endCol: configLen + curCol
              })
            } else {
              exportArr.push({
                value: curObj[item.name],
                startRow: dataRow,
                startCol: currentCol,
                endRow: dataRow,
                endCol: currentCol
              })
            }
            dataRow++
          }
        })
        var dh = XlsxUtil.getDownloadRangesHelper(exportArr)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download('座席满意度调查报表' + timeStamp)
      },
      // 处理二级满意度
      renderTwoRow (arr, cur, tableData) {
        let subArr = []
        arr.forEach((item, i) => {
          let dataRow = 3
          subArr.push({
            value: item.displayname,
            startRow: 2, // 开始行
            startCol: cur + i + 1, // 开始列
            endRow: 2, // 结束行
            endCol: cur + i + 1 // 结束列
          })
          for (let k = 0; k < tableData.length; k++) {
            let curObj = tableData[k]
            subArr.push({
              value: curObj[item.name],
              startRow: dataRow,
              startCol: cur + i + 1,
              endRow: dataRow,
              endCol: cur + i + 1
            })
            dataRow++
          }
        })
        return subArr
      },
      exportXlsx (init) {
        var queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        this.$store.dispatch('queryImCsrReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          // 表头
          let headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
          let serverData = mixData(deepClone(res.data), this.formulas) || []
          let sum = []
          if (serverData.length !== 0) {
            sum = this.getTotalData(serverData, headOptions, true)
          }
          let tableData = this.getTableData(serverData, true).concat(sum)

          var ConfigsTemp = []
          headOptions.Config && headOptions.Config.forEach(config => {
            ConfigsTemp.push(config)
            if (config.name === 'agentName') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agentExten'
              })
            } else if (!this.exCludesKey.includes(config.name) && config.name.indexOf('_') === -1) {
              ConfigsTemp.push({
                show: config.show,
                displayname: config.displayname + '占比',
                name: config.name + '_rate'
              })
            }
          })
          if (init === 'Front') {
            headOptions.Config = [...ConfigsTemp, ...this.formulasConfig]
            this.dealDetailExport(tableData, headOptions.Config, ConfigsTemp.length)
            return
          }
          headOptions.Config = ConfigsTemp

          let headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

          let dh = XlsxUtil.getDownloadHelper(headers, tableData)
          let timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.imReportCsr') + timeStamp)
        })
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        if (this.isShowDetail) {
          exportReportPdf({title: this.$t('report.webchat') + searchTime(this.query), id: 'crsDetail'})
        } else {
          exportReportPdf({title: this.$t('report.webchat') + searchTime(this.query), id: this.id})
        }
      }
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      let type = this.flag ? 'ecommerceAccessId' : 'accessIds'
      this.$store.dispatch('getCache', { type: type }).then(accessIds => {
        this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
        this.search()
      })
      this.$store.dispatch('getDicCache', {type: 'mailQueues'}).then((res) => {
        if (res && res.success) {
          this.mailQueues = res.data
        }
      })
      this.$store.dispatch('getCache', {type: 'depts'}).then((dept) => {
        this.depts = dept.filter(item => {
          return item.pId
        })
        this.depts.push({
          name: '未分配部门',
          treePath: 'noDept'
        })
      })
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .csr
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .el-select
        width 600px
    .agent_search
      .wrap_conti
        margin 14px 0 0 0px
        .chan_ag
          float left
          margin-right 16px
        .el-radio
          margin-right 30px
        .dept
          .el-radio
            margin-right 42px
    .skill
      margin-top 14px
      .ski
        margin-right 26px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 15px
      border-radius 50%
      margin 0px 0 0 6px
      .iconfont
        border none
        font-size 10px
        color $c-main
    .agen
      margin 14px 0 0px 18px
      .el-select
        width 220px
    .search
      margin-bottom 34px
      .el-select
        width 400px
      .el-checkbox
        margin-left 16px
    .age
      display inline-block
      height 36px
      line-height 36px
      margin-right 16px
    .export
      .pdf
        margin-right 10px
    .tab
      .deploy
        .tip
          margin-left 0px
    .agen
      margin-top 14px
      .age
        display inline-block
        height 28px
        line-height 28px
        margin 0 22px 0 0
      .el-select
        width 600px
</style>
